import os
import requests
import json
import openpyxl
dir_name = "无职转生"
url = "https://games.mobileapi.hupu.com/1/8.0.1/bplcommentapi/bff/bpl/score_tree/groupAndSubNodes?nodeId=1695022&queryType=hot&page=1&pageSize=92"
def scrapy(file_name, url):
    dir_name = file_name
    os.makedirs(dir_name)
    headers = {
        'user-agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
    }
    res = requests.get(url=url, headers=headers)
    data = res.text
    data = json.loads(data)
    list_data = data["data"]["nodePageResult"]["data"]

    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Scores"
    ws.append(["名字", "平均分", "评分人数","评论","图片"])
    for item in list_data:
        name = item["node"]["name"]
        score_avg = (item["node"]["scoreAvg"])
        score_person_count = (item["node"]["scorePersonCount"])
        try:
            comment = item["node"]["hottestComments"][0]
        except Exception as e:
            comment = ''
        image = item["node"]["image"][0]
        ws.append([name, score_avg, score_person_count, comment,image])
        continue
    excel_filename = f"{dir_name}/scores.xlsx"
    wb.save(excel_filename)
    print(f"数据已保存到 {excel_filename}")
if __name__== "__main__" :
    scrapy(dir_name, url)